<template>
  <div class="image-generator">
    <el-container>
      <!-- 左侧生成区域 -->
      <el-main>
        <div class="generator-container">
          <h1>生成图片</h1>

          <!-- 控件区域 -->
          <div class="controls">
            <el-form :model="form" label-width="100px">
              <el-form-item label="随机种子">
                <el-input-number
                  v-model="form.seed"
                  :min="1"
                  :max="999999"
                  placeholder="输入种子值" />
              </el-form-item>

              <el-form-item label="截断Psi">
                <el-tooltip
                  content="控制生成图像的质量和多样性平衡：
                          较小值（0.5-0.7）产生更保守、高质量的图像；
                          较大值（0.8-1.0）产生更多样化的图像"
                  placement="right"
                  effect="light"
                  :show-after="0">
                  <template #default>
                    <el-input-number
                      v-model="form.truncationPsi"
                      :min="0"
                      :max="2"
                      :step="0.1"
                      :precision="2"
                      placeholder="输入截断值" />
                  </template>
                </el-tooltip>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  @click="generateImage"
                  :loading="isLoading">
                  {{ isLoading ? '生成中...' : '生成图片' }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 显示生成的图片 -->
          <div v-if="imageUrl" class="result">
            <h2>生成的图片:</h2>
            <el-image
              :src="imageUrl"
              :preview-src-list="[imageUrl]"
              fit="contain"
              class="generated-image"
              @error="handleImageError">
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
          </div>

          <!-- 显示错误信息 -->
          <el-alert
            v-if="error"
            :title="error"
            type="error"
            show-icon
            :closable="false"
            class="error-alert" />
        </div>
      </el-main>

      <!-- 右侧历史记录 -->
      <el-aside width="350px">
        <div class="history-container">
          <h2 class="history-title">历史生成记录</h2>
          <el-scrollbar class="history-list-scrollbar">
            <div class="history-list">
              <el-card
                v-for="item in historyList"
                :key="item.id"
                class="history-item"
                shadow="hover">
                <el-image
                  :src="item.imageUrl"
                  :preview-src-list="[item.imageUrl]"
                  fit="cover"
                  class="history-image">
                </el-image>
                <div class="history-info">
                  <template v-if="item.seed !== null && item.truncationPsi !== null">
                    <p>种子: {{ item.seed }}</p>
                    <p>Psi: {{ item.truncationPsi }}</p>
                  </template>
                  <template v-else>
                    <p>头像图片</p>
                  </template>
                  <p>时间: {{ formatDate(item.createTime) }}</p>
                  <el-button
                    v-if="item.seed !== null && item.truncationPsi !== null"
                    type="primary"
                    link
                    @click="useHistoryParams(item)">
                    使用这些参数
                  </el-button>
                </div>
              </el-card>
            </div>
          </el-scrollbar>
          <!-- 分页器 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.page"
              :page-size="pagination.limit"
              :total="pagination.total"
              @current-change="handlePageChange"
              layout="prev, pager, next"
              background />
          </div>
        </div>
      </el-aside>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { predictImage, getHistory, type GeneratedImage } from '@/api/image'
import type { ApiResponse } from '@/types/api'

const form = ref({
  seed: 42,
  truncationPsi: 1.0
})
const imageUrl = ref<string | null>(null)
const error = ref<string | null>(null)
const isLoading = ref(false)
const historyList = ref<GeneratedImage[]>([])
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

// 获取历史记录
const fetchHistory = async () => {
  try {
    const response = await getHistory({
      page: pagination.value.page,
      limit: pagination.value.limit
    })

    if (response.code === 200) {
      historyList.value = response.data
      pagination.value.total = response.data.length
    } else {
      ElMessage.error(response.msg || '获取历史记录失败')
    }
  } catch (err) {
    console.error('获取历史记录失败:', err)
    ElMessage.error('获取历史记录失败')
  }
}

// 生成图片
const generateImage = async () => {
  try {
    error.value = null
    imageUrl.value = null
    isLoading.value = true

    const response = await predictImage({
      seed: parseInt(String(form.value.seed)),
      truncationPsi: parseFloat(String(form.value.truncationPsi))
    })

    if (response.code === 200) {
      // 确保使用正确的图片URL路径
      imageUrl.value = response.data.imageUrl
      await fetchHistory() // 刷新历史记录
      ElMessage.success('图片生成成功')
    } else {
      error.value = response.msg || '生成图片失败'
      ElMessage.error(error.value)
    }
  } catch (err) {
    console.error('请求失败:', err)
    error.value = '请求失败，请稍后再试'
    ElMessage.error(error.value)
  } finally {
    isLoading.value = false
  }
}

// 使用历史参数
const useHistoryParams = (item: GeneratedImage) => {
  // 只有当seed和truncationPsi存在时才使用
  if (item.seed !== null && item.truncationPsi !== null) {
    form.value.seed = item.seed
    form.value.truncationPsi = item.truncationPsi
    ElMessage.success('已应用历史参数')
  } else {
    ElMessage.warning('该记录没有可用的生成参数')
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 处理图片加载错误
const handleImageError = () => {
  error.value = '图片加载失败'
  ElMessage.error(error.value)
}

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.page = page
  fetchHistory()
}

onMounted(() => {
  fetchHistory()
})
</script>

<style scoped>
.image-generator {
  height: 100vh; /* Ensure full viewport height */
  background-color: #f5f7fa;
  display: flex; /* Use flex to manage el-container height */
  flex-direction: column;
  overflow: hidden; /* Prevent image-generator from scrolling */
}

.el-container {
  flex: 1; /* Allow el-container to fill remaining height */
  height: 100%; /* Important for flex item */
  overflow: hidden; /* Prevent el-container from scrolling */
}

.generator-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  /* Potentially add max-height and overflow if this section can exceed viewport height */
}

.controls {
  margin: 20px 0;
}

.result {
  margin-top: 30px;
}

.result h2 {
  margin-bottom: 20px;
}

.generated-image {
  width: 100%;
  max-width: 400px;
  height: 400px;
  margin: 0 auto;
  display: block;
}

.generated-image :deep(img) {
  object-fit: contain;
  width: 100%;
  height: 100%;
}

.error-alert {
  margin-top: 20px;
}

.history-container {
  background-color: white;
  border-left: 1px solid #e6e6e6;
  height: 100%; /* Fill aside height */
  display: flex; /* Use flex for history container */
  flex-direction: column;
  overflow: hidden; /* Hide any potential overflow from this container */
}

.history-title {
  padding: 15px;
  margin: 0;
  border-bottom: 2px solid #e6e6e6;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  flex-shrink: 0; /* Prevent title from shrinking */
}

.history-list-scrollbar {
  flex: 1; /* Allow scrollbar area to fill remaining space */
  /* Calculate height based on container height minus title and pagination */
  height: calc(100% - 60px - 50px); /* Adjust 60px (title height) and 50px (pagination height) as needed */
}

.history-list {
  padding: 15px;
}

.history-item {
  margin-bottom: 15px;
}

.history-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.history-info {
  margin-top: 8px;
  font-size: 13px;
  text-align: left;
}

.history-info p {
  margin: 3px 0;
  color: #666;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 150px;
  color: #909399;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.pagination-container {
  padding: 10px 15px;
  display: flex;
  justify-content: center;
  background-color: white;
  border-top: 1px solid #e6e6e6;
  flex-shrink: 0; /* Prevent pagination from shrinking */
}

/* Adjust layout responsiveness */
@media (max-width: 1200px) {
  .generated-image {
    max-width: 350px;
    height: 350px;
  }
}

@media (max-width: 768px) {
  .generated-image {
    max-width: 300px;
    height: 300px;
  }
}
</style>
